{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Data Generation\n",
    "此notebook主要用于使用文心大模型产生文本数据以便于进一步分析或者作为训练蒸馏数据，欢迎大家使用自己使用自己的开源模型向文心一言蒸馏。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "import erniebot,os,math,time\n",
    "from typing import List\n",
    "erniebot.api_type = 'aistudio'\n",
    "erniebot.access_token = '<EB_ACCESS_TOKEN>'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "def transform_list(s):\n",
    "    md_content = s.split('```')[1]\n",
    "    md_content = md_content[md_content.find('\\n'):]\n",
    "    md_content = md_content.replace('\\n','').replace(' ','')\n",
    "    return md_content[md_content.find('['):]\n",
    "\n",
    "def get_data(query:str) -> str:\n",
    "    chat_message = [\n",
    "        {'role': 'user', 'content': f\"{query}，结果请用python的列表返回\"}\n",
    "    ]\n",
    "    response = erniebot.ChatCompletion.create(model='ernie-bot-4', \n",
    "                                            messages=chat_message)\n",
    "\n",
    "    return eval(transform_list(response.get_result()))\n",
    "\n",
    "wenxin_reviews = get_data(\"请帮我生成二十条关于百度文心一言产品的用户评论\")\n",
    "map_reviews = get_data(\"请帮我生成二十条关于百度地图的用户评论\")\n",
    "wenku_reviews = get_data(\"请帮我生成二十条关于百度网盘的用户评论\")\n",
    "trans_reviews = get_data(\"请帮我生成二十条关于百度翻译的用户评论\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>reviews</th>\n",
       "      <th>type</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>百度网盘非常方便，我可以随时随地访问我的文件。</td>\n",
       "      <td>wangpan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65</th>\n",
       "      <td>我觉得百度翻译的界面很简洁，使用起来很顺畅。</td>\n",
       "      <td>translation</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>36</th>\n",
       "      <td>地图的夜间模式很舒适，晚上使用时不会刺眼。</td>\n",
       "      <td>map</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>43</th>\n",
       "      <td>百度网盘的安全措施做得很好，我可以放心地保存我的文件。</td>\n",
       "      <td>wangpan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>70</th>\n",
       "      <td>百度翻译对于日常交流来说足够好了，但我不会用它来翻译重要的商业文档。</td>\n",
       "      <td>translation</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>48</th>\n",
       "      <td>我觉得免费用户的存储空间有点小，但付费用户可以获得更多的存储空间。</td>\n",
       "      <td>wangpan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>百度地图的海外地图数据也很全，适合出国旅行时使用。</td>\n",
       "      <td>map</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>49</th>\n",
       "      <td>百度网盘是一个很好的云存储服务，我会继续使用它。</td>\n",
       "      <td>wangpan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>百度网盘的文件分类和整理功能非常出色。</td>\n",
       "      <td>wangpan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>我使用百度文心一言的感受是，它的自然语言处理能力非常强大。</td>\n",
       "      <td>wenxin</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                               reviews         type\n",
       "40             百度网盘非常方便，我可以随时随地访问我的文件。      wangpan\n",
       "65              我觉得百度翻译的界面很简洁，使用起来很顺畅。  translation\n",
       "36               地图的夜间模式很舒适，晚上使用时不会刺眼。          map\n",
       "43         百度网盘的安全措施做得很好，我可以放心地保存我的文件。      wangpan\n",
       "70  百度翻译对于日常交流来说足够好了，但我不会用它来翻译重要的商业文档。  translation\n",
       "48   我觉得免费用户的存储空间有点小，但付费用户可以获得更多的存储空间。      wangpan\n",
       "34           百度地图的海外地图数据也很全，适合出国旅行时使用。          map\n",
       "49            百度网盘是一个很好的云存储服务，我会继续使用它。      wangpan\n",
       "50                 百度网盘的文件分类和整理功能非常出色。      wangpan\n",
       "1        我使用百度文心一言的感受是，它的自然语言处理能力非常强大。       wenxin"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.concat(\n",
    "    [\n",
    "        pd.DataFrame({'reviews':wenxin_reviews,'type':['wenxin' for _ in range(len(wenxin_reviews))]}),\n",
    "        pd.DataFrame({'reviews':map_reviews,'type':['map' for _ in range(len(wenxin_reviews))]}),\n",
    "        pd.DataFrame({'reviews':wenku_reviews,'type':['wangpan' for _ in range(len(wenxin_reviews))]}),\n",
    "        pd.DataFrame({'reviews':trans_reviews,'type':['translation' for _ in range(len(wenxin_reviews))]}),  \n",
    "    ]\n",
    ").reset_index(drop = True)\n",
    "\n",
    "df.sample(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Embedding\n",
    "将生成的数据向量化，详细操作请参考[Embedding](03-Embedding.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_embedding(word: List[str]) -> List[float]:\n",
    "    if len(word) <= 16:\n",
    "        embedding = erniebot.Embedding.create(\n",
    "                                            model = 'ernie-text-embedding',\n",
    "                                            input = word\n",
    "                                            ).get_result()\n",
    "    else:\n",
    "        size = len(word)\n",
    "        embedding = []\n",
    "        for i in range(math.ceil(size / 16)):\n",
    "            embedding.extend(erniebot.Embedding.create(model = 'ernie-text-embedding', input = word[i*16:(i+1)*16]).get_result())\n",
    "            time.sleep(1) # 防止访问频繁报错\n",
    "    return embedding\n",
    "\n",
    "reviews_embedding = get_embedding(df.reviews.to_list())\n",
    "\n",
    "assert len(reviews_embedding) == df.shape[0] 'mismatch'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将生成的embedding存储为npy文件以便使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "np.save('./data/review_embedding.npy',np.array(reviews_embedding))\n",
    "df.to_csv('./data/reviews.csv',index = False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ernie",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
